/* Esta clase se utiliza para capturar
 * el flujo de bytes de entrada y salida
 * del puerto serie, abierto mediante la 
 * clase CommConnection
 */

package org.util;

import javax.microedition.io.CommConnection;
import javax.microedition.io.Connector;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class SerialPort {
	private CommConnection conn = null;
    private InputStream in = null;
    private OutputStream out = null;
	public static final boolean PARITY_NONE = false;
	public static final boolean PARITY_EVEN = true;
    
    public SerialPort(int number, int baudrate, int dataBits, boolean parity, int stopBits) throws IOException{
    	String paridad;
    	paridad = (parity)? "even":"none";
    	conn = (CommConnection)Connector.open("comm:COM"+number+";bitsperchar="+dataBits+";stopbits="+stopBits+";parity="+paridad);
	    conn.setBaudRate(baudrate);
    }
    public boolean isOpen() {
    	if (conn == null) return false;
    	else return true;
    }
    public void writeBytes(byte buf[],int start, int count) {    	
        try {
    	    if (out==null) out = conn.openOutputStream();
    	    out.flush();
    	    if (this.isOpen()) out.write(buf, start, count);
		} catch (IOException e) {
			System.out.println("Writing process failed! ");
			e.printStackTrace();
		}
    }
    public int readBytes(byte buf[],int start, int count) {
        int ch=0;
    	try {
    		if (in==null) in = conn.openInputStream();
        	//ch = in.read();
			ch = in.read(buf, start, count);//SE PIERDE EN ESTA INSTRUCTION
		} catch (IOException e) {
				System.out.println("Reading process failed! ");
				e.printStackTrace();
		}
        System.out.println("Lectura: "+(char)ch);
        return ch;
      		//return in.read(buf, start, count);    	
    }
    public int readCheck() throws IOException {
    	in = conn.openInputStream();
		return in.available();  
    }
    public void close() throws IOException{
    	out.close();
    	in.close();
		conn.close();
    }
    public void flush() throws Exception {
    	out.flush();
    }  
}
